package net.tngou.crawler.drug;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.math.NumberUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import net.tngou.c4j.util.HttpUtil;
import net.tngou.cache.CacheEngine;
import net.tngou.cache.TgCacheEngine;
import net.tngou.crawler.util.StringUtil;

/**
 * 康德乐大药房
 * @author tngou@tngou.net
 *
 */
public class CN_COM_Baiji extends BaseCrawler implements CrawlerDrug{
	private static final Logger log= LoggerFactory.getLogger(CN_COM_Baiji.class);

	private String url="https://www.baiji.com.cn/goods-{}.html";
	
//	@Override
//	public List<URL> urls() {
//		List<URL> list = new ArrayList<>();
//		for (int i=0;i<SIZE;i++) {	
//			try {
//				URL u = new URL(StringUtil.replace(url, "{}", getId()+""));
//				list.add(u);
//			} catch (MalformedURLException e) {
//				e.printStackTrace();
//			}
//			
//		}
//		return list;
//	}
	@Override
	public JSONObject getJson(URL url) {
		log.info("请求页面:{}",url.toString());
		Document doc = HttpUtil.get(url.toString());
		if(doc==null||doc.text().indexOf("暂未经营该药品")>0)return null;
		json.put("url", url.toString());
		json.put("onlinepharmacy", onlinepharmacy);
		//唯一值
		json.put("un",url.toString().split("-")[1].replaceAll(".html", "-").split("-")[0]);
		//标签
		Elements crumbs = doc.getElementsByClass("crumbs");
		if(crumbs.first()!=null)
		{
			Elements as = crumbs.first().getElementsByTag("a");
			List<String> list = new ArrayList<>();
			for (int i = 1; i < as.size(); i++) {
				list.add(as.get(i).text());
			}	
			json.put("tag", list);
		}
		
		//价格
		Element price = doc.getElementById("ECS_SHOPPRICE");
		if(price!=null)
		{			
			json.put("price", getPrice(price.text()));			
		}
		//图片
		Element showbox = doc.getElementById("showbox");
		if(showbox!=null)
		{
			Elements imgs = showbox.getElementsByTag("img");
			List<String> list = new ArrayList<>();
			imgs.forEach(e->{
				String src = e.attr("src");
				if(StringUtil.isNotEmpty(src))
				{
					list.add(src);
				}
			});
			json.put("picture", list);
		}
		//说明书
		Elements padtb20 = doc.getElementsByClass("padtb20");
		if(padtb20.first()!=null)
		{
			Elements tables = padtb20.first().getElementsByTag("table");
			if(tables.first()!=null)
			{
			
				JSONObject instructions =instructions(tables.first());
				
				json.put("instructions",instructions );		
			}
			
		}
		
		return json;
	}
	
	public JSONObject instructions(Element element) {
		JSONObject json = new JSONObject(true);
	
		Elements trs = element.getElementsByTag("tr");
		for (Element tr : trs) {
			Elements tds = tr.getElementsByTag("td");
			if(tds.size()==2)
			{	
				String key=StringUtil.cleanKey(tds.first().text());
				String value=StringUtil.RemoveEmpty(tds.get(1).text());
				if(tds.first().text().indexOf("药品名称")>0&&tds.get(1).html().indexOf("br")>0)
				{
					Element e = tds.get(1).getElementsByTag("p").first();
					boolean b=true;
					  String[] sts_b = StringUtil.split(e.html(), "<br>");
						for (String s : sts_b) {
							String[] sts = s.split("：");
							if(sts.length==2)
							{
								json.put(StringUtil.cleanKey(sts[0]),StringUtil.RemoveEmpty(sts[1]));
								b=false;
							}
						}
					if(b) {
						json.put(key, value);
					}
					
				}else {
					json.put(key, value);
				}
				
			}
		}
		
		return change(json);
	}

	
	public JSONObject  change(JSONObject ijson) {
		JSONObject rjson = new JSONObject(true);
		Set<String> keys = ijson.keySet();
		String like="";
		if(keys.size()>2)
		{
			int size = keys.size();
			Object[] s= (Object[]) keys.toArray();
			like=like(s[size-3].toString(),s[size-2].toString(),s[size-1].toString());
		}
		if(StringUtil.isNotEmpty(like))
		{
			for (String key : keys) {
				rjson.put(key.replace(like, ""), ijson.get(key));
			}
		}else
		{
			rjson=ijson;
		}	
		
		return name_number(rjson);
	}
	private  String  like(String str1,String str2,String str3)
	 {
	  String s="";
	  for(int i=0;i<str1.length();i++)//获取第一个字符串中的单个字符
	   for(int j=0;j<str2.length();j++)//获取第er个字符串中的单个字符  
	 {
		   for(int k=0;k<str3.length();k++)//获取第er个字符串中的单个字符  
			 {
			    if(str1.charAt(i)==str2.charAt(j)&&str2.charAt(j)==str3.charAt(k))//判断字符是否相同
			     s=s+str1.charAt(i);
			 }
	   }
	  return s;
	 }

	
}
